<template>
  <div id="market_freegift_detail">
    <div class="detail-table" v-if='isShow'>
      <Row>
        <Col span="24" class="detail-table__col detail-table__title">促销管理详情</Col>
      </Row>
      <Row>
        <Col span="12" class="detail-table__col">
          活动编号：{{activityDetail.activityCode}}
        </Col>
        <Col span="12" class="detail-table__col">
          活动名称：{{activityDetail.activityName}}
        </Col>
      </Row>
      <Row>
        <Col span="12" class="detail-table__col">
          开始时间：{{(activityDetail.startTime || '').replace(/-/g, '/')}}
        </Col>
        <Col span="12" class="detail-table__col">
          结束时间：{{(activityDetail.endTime || '').replace(/-/g, '/')}}
        </Col>
      </Row>
      <Row type='flex' style="border-bottom: 1px solid #E9E9E9;">
        <Col span="12" class="detail-table__col" style="display: flex">
          <p style="width: 65px">面向门店：</p>
          <p style="flex: 1">{{activityDetail.faceShop}}</p>
        </Col>
        <Col span="12" class="detail-table__col" style="flex: 1">
          面向会员：{{activityDetail.faseMember}}
        </Col>
      </Row>
      <Row>
        <Col span="12" class="detail-table__col">
          营销渠道：{{activityDetail.channel | getChannelsName}}
        </Col>
        <Col span="12" class="detail-table__col">
          适用产品：{{activityDetail.ableProduct | getProductName}}
        </Col>
      </Row>
      <div>
        <div v-for='(item,idx) in activityDetail.processRules' :key='idx'>
          <Row>
            <Col span="24" class="detail-table__col">
              <span v-for='(ele,i) in activityDetail.ableProduct' :key='i'>
                <span>{{activityDetail.ableProduct[i] === '3' ? '游戏币': activityDetail.ableProduct[i] === '4' ? '游戏券': activityDetail.ableProduct[i] === '5' ? '游戏卡' : activityDetail.ableProduct[i] === '6' ? '休闲项目': activityDetail.ableProduct[i] === '7' ? '小商品': activityDetail.ableProduct[i] === '22' ? 'SVIP会员' : ''}}：</span>
                <span>金额满{{item.values[i].value1}}元,</span>
                <span v-if="activityTypeId === '6'">赠送礼包</span>
                <span v-if="activityTypeId === '7'">减{{item.values[i].value2}}元</span>
                <span v-if="activityTypeId === '8'">打{{item.values[i].value2}}折</span>
                <span v-show='i !== (activityDetail.ableProduct.length-1)' style="margin: 0 10px">|</span>
              </span>
            </Col>
          </Row>
          <Row v-if="activityTypeId === '6'">
            <Col span="24" class="detail-table__col">赠送积分：{{item.integral}}</Col>
          </Row>
          <dl class="detail-table__col" v-if="activityTypeId === '6'">
            <dt>
              <p class="coupon-name">优惠券名称</p>
              <p>类型</p>
              <p class="coupon-name">有效期</p>
              <p>使用渠道</p>
              <p>最低使用金额(元）</p>
              <p>面额</p>
            </dt>
            <dd style="margin-top: 15px" v-for='(ele,i) in item.giftList' :key='i'>
              <p class="coupon-name">{{ele.giftName}}</p>
              <p>{{ele.giftType == 0 ? '代金券': ele.giftType == 1 ? '折扣券': ele.giftType == 2 ? '赠币券' : ''}}</p>
              <p class="coupon-name">{{ele.expirationType == 0? ele.dayNum + '天': ele.expirationType == 1?(ele.startTime + '至' + ele.endTime):''}}</p>
              <p>{{ele.channel | getChannelsName}}</p>
              <p>{{ele.accumAmount}}</p>
              <p>
                <span>{{ele.giftType == 1 ? ele.promotionAmount * 10 : ele.promotionAmount}}</span>
                <span>{{ele.giftType == 0 ? '元': ele.giftType == 1 ? '折': ele.giftType == 2 ? '枚' : ''}}</span>
              </p>
            </dd>
          </dl>
        </div>
      </div>
      <Row>
        <Col span="24" class="detail-table__col">
          活动状态：{{activityDetail.status === 0 ? '未开始' : activityDetail.status === 1 ? '进行中' : activityDetail.status === 2 ? '已结束' : ''}}
        </Col>
      </Row>
      <!-- <Row v-if="activityTypeId === '6'">
        <Col span="12" class="detail-table__col">
          推送微信消息：{{wechat.name}}
        </Col>
        <Col span="12" class="detail-table__col">
          推送短信消息：{{message.name}}
        </Col>
      </Row>
      <Row v-if="activityTypeId === '6'">
        <Col span="12" class="detail-table__col">
          微信消息模板：{{wechat.content}}
        </Col>
        <Col span="12" class="detail-table__col">
          短信消息模板：{{message.content}}
        </Col>
      </Row> -->
      <Row type='flex' style="border-bottom: 1px solid #E9E9E9;" v-if="activityTypeId === '6'">
        <Col span="12" class="detail-table__col" style="display: flex">
          <p style="width: 85px">推送短信消息：</p>
          <p style="flex: 1">{{message.name}}</p>
        </Col>
        <Col span="12" class="detail-table__col" style="display: flex">
          <p style="width: 85px">短信消息模板：</p>
          <p style="flex: 1">{{message.content}}</p>
        </Col>
      </Row>
      <Row>
        <Col span="12" class="detail-table__col">
          创建时间：{{(activityDetail.createTime || '').replace(/-/g, '/')}}
        </Col>
        <Col span="12" class="detail-table__col">
          编辑时间：{{(activityDetail.updateTime || '').replace(/-/g, '/')}}
        </Col>
      </Row>
      <Row>
        <Col span="12" class="detail-table__col">
          创建人：{{activityDetail.creatorName}}
        </Col>
        <Col span="12" class="detail-table__col">
          编辑人：{{activityDetail.modifierName}}
        </Col>
      </Row>
      <Row>
        <Col span="24" class="detail-table__col">
          <table>
            <tr>
              <td width="72" valign="top">活动说明：</td>
              <td style="word-break:break-all;">{{activityDetail.remark}}</td>
            </tr>
          </table>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
import { getOrgAllTree } from '@/api/system/org'
import { detailfreeGift } from '@/api/market/freegift.js'
import enumsMixin from '../enums.js'
import { getMessages } from '@/api/market/message'
import axios from 'axios'
let that
export default {
  name: 'market_freegift_detail',
  mixins: [enumsMixin],
  data () {
    return {
      isShow: false,
      activityId: '',
      activityTypeId: '',
      activityDetail: '',
      faceShopList: [],
      sendWechats: [],
      sendMessages: [],
      wechat: {
        name: '无',
        content: ''
      },
      message: {
        name: '无',
        content: ''
      }
    }
  },
  beforeCreate () {
    that = this
  },
  filters: {
    getChannelsName (value) {
      if (value) {
        let arr
        if (typeof value === 'string') {
          arr = value.split(',')
        } else {
          arr = value
        }
        return arr.map((value) => {
          const result = that.channelList.filter(item => +item['value'] === +value)
          return result[0] ? result[0]['label'] : ''
        }).join(',')
      }
      return ''
    },
    getProductName (value) {
      if (value) {
        let arr
        if (typeof value === 'string') {
          arr = value.split(',')
        } else {
          arr = value
        }
        return arr.map((value) => {
          const result = that.categoryList.filter(item => +item['value'] === +value)
          return result[0] ? result[0]['label'] : ''
        }).join(',')
      }
      return ''
    }
  },
  methods: {
    detailFuc () {
      detailfreeGift({
        merchantId: this.$store.state.user.merchantId,
        activityId: this.activityId
      }).then(res => {
        this.isShow = true
        if (res.data.status === 200) {
          let data = res.data.data
          let product = []
          let level = []
          if (data.rules.length > 0) {
            product = data.rules.map((item, idx) => {
              return item.matchRules.itemId[0]
            })
            data.rules[0].processRules.forEach((val, index) => {
              let obj = {
                values: [],
                giftList: [],
                integral: ''
              }
              data.rules.forEach((item, idx) => {
                if (this.activityTypeId === '6') {
                  obj.values.push({ value1: item.processRules[index].accumAmount })
                  let giftArr = item.processRules[index].giftList
                  let integral = giftArr.filter(cat => cat.giftType === 3)
                  obj.integral = integral.length > 0 ? integral[0].amount + '' : ''
                  obj.giftList = giftArr.filter(cat => cat.giftType !== 3).map(gift => {
                    return gift
                  })
                } else if (this.activityTypeId === '7') {
                  obj.values.push({ value1: item.processRules[index].accumAmount + '', value2: item.processRules[index].promotionAmount + '' })
                } else if (this.activityTypeId === '8') {
                  obj.values.push({ value1: item.processRules[index].accumAmount + '', value2: (item.processRules[index].promotionAmount + '').length > 3 ? (item.processRules[index].promotionAmount * 10).toFixed(1) + '' : (item.processRules[index].promotionAmount * 10 + '') })
                }
              })
              level.push(obj)
            })
          }
          this.activityDetail = {
            ...data.activityBase,
            channel: data.rules[0].matchRules.channel,
            ableProduct: product, // 产品数组
            processRules: level,
            faceShop: data.rules[0].matchRules.shopId.map(item => {
              this.faceShopList.forEach(ele => {
                if (item === ele.shopId) {
                  item = ele.shopName
                }
              })
              return item
            }).join(','),
            faseMember: data.rules[0].matchRules.memberLevel.map(item => {
              item = 'V' + item
              return item
            }).join(',')
          }
          if (data.templates.length > 0) {
            data.templates.forEach(item => {
              if (item.templateType === 1) {
                this.selectWechatChange(item.templateId)
              } else if (item.templateType === 2) {
                this.selectMessageChange(item.templateId)
              }
            })
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    selectWechatChange (value) {
      if (value) {
        this.sendWechats.forEach(item => {
          if (item.id === value) {
            this.wechat = { content: item.content, name: item.templateName }
          }
        })
      } else {
        this.wechat = {}
      }
    },
    selectMessageChange (value) {
      if (value) {
        this.sendMessages.forEach(item => {
          if (item.id === value) {
            this.message = { content: item.content, name: item.templateName }
          }
        })
      } else {
        this.message = {}
      }
    },
    // 递归取门店
    getStore (list) {
      list.forEach(ele => {
        if (ele.childList.length > 0) {
          this.getStore(ele.childList)
        } else {
          if (ele.orgType === 1) {
            this.faceShopList.push({
              shopId: ele.id,
              shopName: ele.orgName
            })
          }
        }
      })
    },
    // 获取模板内容
    getEnums (templateType) {
      getMessages({
        templateType: templateType,
        merchantId: this.$store.state.user.merchantId,
        suitableType: this.activityTypeId,
        status: 1
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.sendMessages = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getShopList () {
      let storeParam = { merchantId: this.$store.state.user.merchantId, orgType: 1 }
      if (this.activityTypeId === '6') {
        let msgParam = { merchantId: this.$store.state.user.merchantId, templateType: 2, status: 1, suitableType: this.activityTypeId }
        axios.all([getOrgAllTree(storeParam), getMessages(msgParam)])
          .then(axios.spread((tree, ennms) => {
            if (tree.data.status === 200) {
              this.getStore([tree.data.data])
            } else {
              this.$Message.error(`${tree.data.error}`)
            }
            if (ennms.data.status === 200) {
              this.sendMessages = ennms.data.data || []
            } else {
              this.$Message.error(`${ennms.data.error}`)
            }
            this.detailFuc()
          }))
          .catch(err => {
            this.$Message.error(`${err}`)
          })
      } else {
        getOrgAllTree(storeParam).then(res => {
          if (res.data.status === 200) {
            this.getStore([res.data.data])
            this.detailFuc()
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      }
    }
  },
  created () {
    this.activityId = this.$route.params.id
    this.activityTypeId = this.$route.params.type
    this.getShopList()
  }
}
</script>

<style lang="less">
@import '~@/assets/stylus/detail-table.less';
#market_freegift_detail {
  padding: 40px 80px;
  .detail-table .detail-table__col {
    border-right: 1px solid #E9E9E9;
    padding: 15px 48px 15px 48px;
    margin-bottom: 0;
  }
  dl {
    border-bottom: 1px solid #DCDEE2;
    dt,dd{
      display: flex;
      align-items:center;
      p{
        width: 20%;
      }
      .coupon-name {
        width: 130px;
        margin-right: 70px;
      }
    }
  }
}
</style>
